package org.mytools.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 文件操作辅助类
 * 
 * @author Jacky.L
 * 
 */
public class FileUtils {

	/**
	 * 创建一个新的文件，该文件包含的文件目录也会被同时创建
	 * 
	 * @param fullname
	 *            包含文件路径的文件名称
	 * @return 成功创建地文件
	 */
	public static File createFile(String fullname) {
		File file = new File(fullname);
		createPath(file.getParent());

		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}

		return file;
	}

	/**
	 * 创建文件目录
	 * 
	 * @param path
	 *            文件目录
	 */
	public static void createPath(String path) {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	public static void writeFile(File file, byte[] bytes) {
		OutputStream writer = null;
		try {
			writer = new BufferedOutputStream(new FileOutputStream(file));
			writer.write(bytes);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (writer != null) {
					writer.flush();
					writer.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

}
